<template>
    <app-section :loading="pageLoading">
        <van-nav-bar
                :title="title"
                @click-left="backRoute"
                @click-right="saveSelected"
                left-arrow
                left-text="返回"
                right-text="确定">
        </van-nav-bar>

        <van-collapse v-model="queryOpen" v-if="queryInfo && queryInfo.length>0">
            <van-collapse-item name="1">
                <template slot="title">
                    <span v-if="queryOpen.indexOf('1')>=0" style="font-style: italic;font-size: 12px">点击折叠查询条件</span>
                    <span v-else style="font-style: italic;font-size: 12px">点击展开查询条件</span>
                </template>
                <template>
                    <van-field
                            v-for="(item,index) in queryInfo"
                            :key="index"
                            clearable
                            v-model="queryParam[item.field]"
                            :placeholder=" '请输入'+item.label "
                            @input="doQuery">
                    </van-field>
                </template>

            </van-collapse-item>
        </van-collapse>



        <van-pull-refresh v-model="pullLoading" @refresh="onRefresh">
            <van-checkbox-group v-model="selectedList">

                <van-list
                        v-model="listLoading"
                        :finished="listFinished"
                        :finished-text="finishedText"
                        :error.sync="listError"
                        error-text="请求失败，点击重新加载"
                        @load="onLoad()">

                    <van-cell
                            clickable
                            v-for="(item,index) in rpDataList"
                            :key="index"
                            @click="toggleChecked(index)">
                        <van-checkbox
                                ref="cbRef"
                                slot="icon"
                                :name="item">
                        </van-checkbox>
                        <span slot="title" class="cell-content-cust">
                           <div v-for="(col,colIndex) in rpColumnList" :key="colIndex">
                               {{ col.title }}：{{ getCellText(item,col) }}
                           </div>
                        </span>
                    </van-cell>

                </van-list>

            </van-checkbox-group>
        </van-pull-refresh>

    </app-section>
</template>

<script>
  import AppSection from '@/components/AppSection'
  import { getAction } from "@/api";
  import lodashUtil from 'lodash/object'
  import debounce from 'lodash/debounce';

  export default {
    name: "AppReportList",
    components:{
      AppSection
    },
    props:{
      code:{
        type: String,
        default: '',
        required: false
      },
      dest:{
        type: String,
        default: '',
        required: false
      },
      showFields:{
        type: String,
        default: '',
        required: false
      },

      multi:{
        type: Boolean,
        default: false,
        required: false
      }
    },
    data(){
      this.doQuery = debounce(this.doQuery, 1000);//消抖
      return {
        pageLoading:false,
        title:'',

        pullLoading:false,
        selectedList:[],

        listLoading: false,
        listFinished:false,
        finishedText:'没有更多了',
        listError:false,

        pageNo:1,
        pageSize:10,
        url:{
          getColumns: '/online/cgreport/api/getRpColumns/',
          getData: '/online/cgreport/api/getData/',
          getQueryInfo: '/online/cgreport/api/getQueryInfo/'
        },

        rpConfigId:'',
        rpColumnList:[],
        rpDataList:[],
        dictOptions:{},
        queryInfo:[],
        loadColumnFlag:false,
        loadQueryFlag: false,

        queryParam:{},
        queryOpen:[]

      }
    },
    created(){
      this.loadColumnFlag = false
      this.loadQueryFlag = false
    },
    methods:{
      backRoute(){
        this.$emit("back")
      },
      saveSelected(){
        console.log(this.selectedList);
        let arr = [];
        let fields = this.showFields.split(',');
        for(let item of this.selectedList){
          arr.push(lodashUtil.pick(item,fields));
        }
        this.$emit('ok',arr)
      },
      getCellText(item,col){
        return item[col.dataIndex];
      },
      onRefresh(){
        this.loadData(1).then(()=>{
          this.pullLoading=false
        })
      },
      doQuery(){
        this.loadData(1)
      },
      toggleChecked(index){
        this.$refs.cbRef[index].toggle();
      },
      clearAll(){
        this.selectedList=[]
      },
      loadColumnsInfo(){
        return new Promise(resolve => {
          if(this.loadColumnFlag === true){
            resolve()
          }else{
            this.firstField = '';
            this.secondField = '';
            getAction(`${this.url.getColumns}${this.code}`).then(res=>{
              if(res.success){
                this.loadColumnFlag = true;
                this.dictOptions = res.result.dictOptions;
                this.rpConfigId = res.result.cgRpConfigId;
                this.title = res.result.cgRpConfigName;
                let currColumns = [];
                console.log(res.result);
                for(let c of res.result.columns){
                    if(this.showFields.indexOf(c.dataIndex)>=0){
                      currColumns.push(c)
                    }
                }
                this.rpColumnList = [...currColumns];
                this.initQueryInfo();
                /*for(let a=0;a<currColumns.length;a++){
                  if(currColumns[a].customRender){
                    let dictCode = currColumns[a].customRender;
                    currColumns[a].customRender=(text)=>{
                      return filterMultiDictText(this.dictOptions[dictCode], text+"");
                    }
                  }
                }*/

                //this.table.columns = [...currColumns]
               // this.loadData(1)
                resolve();
              }
            })
          }

        })


      },

      initQueryInfo() {
        getAction(`${this.url.getQueryInfo}${this.rpConfigId}`).then((res) => {
          console.log("获取查询条件", res);
          if (res.success) {
            this.queryInfo = res.result;
            for(let item of res.result){
              this.queryParam[item.field] = ''
            }
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      loadData(flag){
        if(flag === 1){
          this.pageNo = 1;
          this.rpDataList = [];
        }
        this.listLoading = true;
        let param = {
          pageNo: this.pageNo,
          pageSize: this.pageSize
        };
        Object.keys(this.queryParam).map(key=>{
          if(this.queryParam[key] && this.queryParam[key].length>0){
            param[key] = '*'+this.queryParam[key]+'*'
          }
        });
        console.log("请求参数 >>",param);
        return new Promise(((resolve, reject) => {
          getAction(`${this.url.getData}${this.rpConfigId}`,param).then(res=>{
            this.listLoading = false;
            console.log("请求结果 >>",res);
            if(res.success){
              // this.$toast.success("加载完成");
              this.pageNo++;
              let arr = res.result.records;
              for(let item of arr){
                this.rpDataList.push(item)
              }

              console.log("arr",arr);
              console.log("arr.length",this.pageSize);
              if(!arr || arr.length<this.pageSize){
                console.log("加载完成!");
                this.listFinished = true;
              }else{
                this.listFinished = false;
              }
              console.log("结果数据", this.rpDataList)
            }else{
              this.listError = true;
            }
            resolve();
          }).catch(e=>{
            console.log("请求错误",e)
            this.listError = true;
            reject();
          })

        }));
      },

      onLoad(){
        this.loadColumnsInfo().then(()=>{
          this.loadData();
        })
      }

    }
  }
</script>

<style lang="less">
.cell-content-cust{
    display:inline-block;
    margin-left: 5px;
    div{
        line-height: 16px;
    }
}
</style>